package com.cfuture08.eweb4j.component.dwz;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.cfuture08.eweb4j.component.dwz.vo.NavMenu;
import com.cfuture08.eweb4j.component.dwz.vo.TreeMenu;
import com.cfuture08.eweb4j.orm.dao.factory.DAOFactory;
import com.cfuture08.eweb4j.orm.sql.constant.OrderType;

public class DWZUtil {
	public static DWZJson getSuccessJson(String message, String navTabId,
			String forwardUrl, String callType, String title) {
		return new DWZJson("200", message, navTabId, forwardUrl, callType,
				title);
	}

	public static DWZJson getFailedJson(String message) {
		return new DWZJson("300", message, "", "", "reload", "");
	}

	public static String getAccordion(String navMenuName) {
		// 1.{navMenuId},根据给定导航菜单名字从数据库获取导航菜单所有信息
		NavMenu navMenu = DAOFactory.getSelectDAO().selectOne(NavMenu.class,
				new String[] { "name" }, new String[] { navMenuName });
		if (navMenu == null) {
			return "";
		}
		return getAccordion(navMenu.getNavMenuId());
	}

	public static String getAccordion(Integer navMenuId) {
		if (navMenuId == null) {
			return "";
		}
		// 2.找出所有pid=0且navMenuId={navMenuId}的菜单
		String id = String.valueOf(navMenuId);
		List<TreeMenu> menuList = DAOFactory.getSearchDAO().searchByExact(
				TreeMenu.class, new String[] { "pid", "navMenuId" },
				new String[] { "0", id }, "rank", OrderType.ASC_ORDER, false);
		// 上者本可以使用级联，将导航菜单关联的所有树形菜单查出来，但是因为涉及到排序，因此没有采用级联。
		if (menuList == null) {
			return "";
		}
		StringBuilder sb = new StringBuilder();
		for (Iterator<TreeMenu> it = menuList.iterator(); it.hasNext();) {
			TreeMenu m = it.next();
			sb.append(new Accordion(m.getName(), DWZUtil.getUlTag(m.getTreeMenuId()))
					.toString());
		}
		return sb.toString();
	}

	public static UlTag getUlTag(long id) {
		return new UlTag("tree treeFolder", createTree(id));
	}

	private static List<LiTag> createTree(long id) {
		List<LiTag> liList = new ArrayList<LiTag>();
		// 3.从数据库中查询所有子节点菜单
		List<TreeMenu> menuList = DAOFactory.getSearchDAO().searchByExact(
				TreeMenu.class, new String[] { "pid" },
				new String[] { String.valueOf(id) }, "rank",
				OrderType.ASC_ORDER, false);
		if (menuList == null) {
			return liList;
		}

		for (Iterator<TreeMenu> it = menuList.iterator(); it.hasNext();) {
			TreeMenu m = it.next();
			liList.add(new LiTag(new ATag(m.getTarget(), m.getRel(), m
					.getReloadFlag(), m.getHref(), m.getName()), new UlTag("",
					createTree(m.getTreeMenuId()))));
		}
		return liList;
	}
}
